﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tycho.Runtime;
using Tycho.Language;
using Tycho.Parser;

namespace Tycho.Transactions {
    public class TransactionalTopLevel : ITopLevel {
        ModuleFrameObject ModuleFrame;
        TransactionalDynamicFrameObject Frame;
        ExpressionLanguage ExpressionLanguage;
        public ModuleManifest ModuleManifest { get; private set; }

        public TransactionalTopLevel (Namespace defaultNamespace) {
            ModuleFrame = new ModuleFrameObject(RuntimeModule.ModuleFrame);
            AnyObject Runtime = AssemblyModuleLoader.LoadAssembly(Namespaces.Runtime, typeof (AnyObject).Assembly);
            ModuleFrame.AddModule(Runtime);
            Frame = new TransactionalDynamicFrameObject(new ModuleSecurityObject(defaultNamespace, ModuleFrame));
            Frame.Transactionalise ();
            ModuleManifest = new ModuleManifest (ModuleFrame);
            ModuleManifest.ModuleLoaders.Add (Namespaces.Runtime, new ImmediateModuleLoader (Runtime));
            ExpressionLanguage = new ExpressionLanguage (ModuleFrame, defaultNamespace);
        }

        public AnyObject Compile (string source) {
            return ExpressionLanguage.CompileOperation (source, null, Frame, ModuleManifest);
        }

        public AnyObject Evaluate (string source) {
            AnyObject op = Compile (source);

            AnyObject result = RuntimeModule.Null;

            result = op.Invoke ();

            return result;
        }

        public AnyObject this [AnyObject name] {
            get {
                return Frame [name];
            }
            set {
                Frame [name] = value;
            }
        }

        public void AddModule (AnyObject module) {
            ModuleFrame.AddModule (module);
        }
    }
}
